<template>
  <div class="flex flex-1 flex-col  px-6 py-5 lg:px-8">
    <div class="h-48 flex flex-col justify-center items-center bg-gradient-to-t from-primary/30 to-secondary/5 rounded-b-[100px]  ">
      <div class="w-full max-w-screen-xl flex flex-col md:flex-row justify-center items-center gap-5" >
        <img v-if="user.avatar!=null" :src="user.avatar"
             :class="['before:content-[123]'
                 ,'w-24 h-24 object-cover rounded-full']" alt="null">
        <div v-else class="flex justify-center items-center w-24 h-24 object-cover rounded-full border text-6xl select-none btn btn-primary">{{ user?.['username'].substring(0,1).toUpperCase() }}</div>

        <div class="flex flex-col  justify-center items-center ">
          <div @click="editUser()"
              class="h-1/2 w-full flex justify-center items-center">
            {{ user?.['username'] }}
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-6 h-6">
              <path stroke-linecap="round" stroke-linejoin="round" d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L10.582 16.07a4.5 4.5 0 01-1.897 1.13L6 18l.8-2.685a4.5 4.5 0 011.13-1.897l8.932-8.931zm0 0L19.5 7.125M18 14v4.75A2.25 2.25 0 0115.75 21H5.25A2.25 2.25 0 013 18.75V8.25A2.25 2.25 0 015.25 6H10" />
            </svg>
          </div>
          <div class="h-1/2 w-full flex justify-center items-center text-xs truncate">{{ user?.['remark'] ?? '' }}</div>
        </div>
      </div>
    </div>
    <router-link :to="'/favorite/'+ user.id"
                 class="hover:bg-primary/20
                 mt-2 w-[80vw] flex justify-center items-center h-24  px-10 my-6 bg-base-100 border border-black/20 shadow-2xl m-auto rounded-2xl">
      <div class="w-1/6 flex justify-center items-center">
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor"
             class="w-10 h-10 fill-pink-400">
          <path stroke-linecap="round" stroke-linejoin="round"
                d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z"/>
        </svg>
      </div>
      <div class="w-5/6 flex justify-center items-center">我喜欢的音乐</div>
    </router-link>

    <!-- sm -->
    <div class="tabs w-full flex justify-center items-end">
      <a @click="isPlaylistOrFavorite=true"
         @click.self="updatePlaylist"
         :class="[{'tab-active':isPlaylistOrFavorite==true},'tab  tab-lg tab-lifted']">创建歌单</a>
      <a @click="isPlaylistOrFavorite=false"
         @click.self="updateFavoritePlaylist"
         :class="[{'tab-active':isPlaylistOrFavorite==false},'tab tab-lg tab-lifted']">收藏歌单</a>
    </div>
    <!--  创建歌单  -->
    <div v-if="isPlaylistOrFavorite" class="m-auto bg-base-100 border border-black/20 shadow-2xl w-[80vw] rounded-2xl h-full">
      <div class="w-full h-16 grid grid-cols-12 grid-rows-1  items-center">
        <div class="col-span-10 flex  justify-start items-center pl-6">创建歌单
          <div class="text-xs text-base-content/50">({{ playlists?.length ?? 0 }}个)</div>
        </div>
        <div class="col-span-2 flex justify-center items-center ">

          <!-- The button to open modal -->
          <label for="addPlaylist" class="">
            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5"
                 stroke="currentColor" class="w-6 h-6 rounded-full hover:btn-ghost">
              <path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/>
            </svg>
          </label>

          <!-- Put this part before </body> tag -->
          <input type="checkbox" id="addPlaylist" class="modal-toggle"/>
          <div class="modal">
            <div class="modal-box relative">
              <label for="addPlaylist" class="btn btn-sm btn-circle absolute right-2 top-2">✕</label>
              <h3 class="text-lg font-bold divider">添加歌单</h3>
              <div class="flex flex-col justify-center items-center my-2 gap-1">
                <p class="max-w-xs w-full text-left">歌单名称</p>
                <input v-model="data_addPlaylist.name" type="text" placeholder="Name Here" class="input input-bordered w-full max-w-xs" />
              </div>
              <div class="flex flex-col justify-center items-center my-2 gap-1">
                <p class="max-w-xs w-full text-left">介绍</p>
                <textarea v-model="data_addPlaylist.remark" class="textarea textarea-bordered w-full max-w-xs" placeholder="Remark ..."></textarea>
              </div>
              <div class="flex flex-row justify-center items-center my-2 gap-1">
                <label for="addPlaylist" @click.self="addPlaylist()" class="btn btn-success w-24">创建</label>
              </div>
            </div>
          </div>


        </div>
      </div>
      <play-list-bar v-for="(playlist,index) in playlists"
                     :key="index"
                     :playlist="playlist"
                     @deleteSuccess="type => {deleteSuccessUpdate(type)}"
                     @update-success="updatePlaylist()"
                     type="playlist">

      </play-list-bar>
      <div class="mt-6"></div>
    </div>

    <!--  收藏歌单  -->
    <div v-else class="m-auto bg-base-100 border border-black/20 shadow-2xl w-[80vw] rounded-2xl h-full">
      <div class="w-full h-16 grid grid-cols-12 grid-rows-1  items-center">
        <div class="col-span-10 flex  justify-start items-center pl-6">收藏歌单
          <div class="text-xs text-base-content/50">({{ favoritePlaylists?.length ?? 0 }}个)</div>
        </div>
        <div class="col-span-2 flex justify-center items-center ">
        </div>
      </div>
      <play-list-bar v-for="(playlist,index) in favoritePlaylists"
                     :key="index"
                     :playlist="playlist"
                     @deleteSuccess="type => {deleteSuccessUpdate(type)}"
                     @update-success="updateFavoritePlaylist()"
                     type="favoritePlaylist">

      </play-list-bar>
      <div class="mt-6"></div>
    </div>
    <div v-if="pageConfig.pages!=0" class="divider mt-[30px] px-10 my-2">我的上传</div>
    <div v-else class="divider mt-[30px] px-10 my-6">暂无上传</div>

    <div class="px-10 my-6 m-auto
     grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-3  xl:grid-cols-6
      grid gap-6">
      <SongCover v-for="(song,index) in pageConfig.songList" :key="song.id" :song="song"></SongCover>
    </div>
    <div v-if="pageConfig.pages!=1 && pageConfig.pages!=0" class="btn-group mx-auto">
      <button class="btn" @click="afterPage">«</button>

      <button :class="[{ 'btn-active' : page === pageConfig.currentPage },'btn']"
              @click="currentPage(page)"
              v-for="(page,index) in pageCollege" :key="index">
        {{ page }}
      </button>

      <button class="btn" @click="nextPage">»</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import SongCover from "../components/SongCover.vue";
import {computed, onBeforeMount, onMounted, reactive, ref} from "vue";
import {hook_getSongByUserId, hook_getSongPage} from "../hook/SongHook.ts";
import {hook_getUser} from "../hook/UserHook.ts";
import DateTimeFormat = Intl.DateTimeFormat;
import {hook_formatDateForDatabaseTime} from "../hook/FormatHook.ts";
import PlayListBar from "../components/PlayListBar.vue";
import {hook_addPlaylist, hook_deletePlaylistById, hook_findPlaylistsByUserId} from "../hook/PlaylistHook.ts";
import {Playlist} from "../hook/Constant.ts";
import {
  hook_deleteFavoritePlaylistByUserId,
  hook_findFavoritePlaylistByUserId,
  hook_findFavoriteSongByUserId
} from "../hook/FavoriteHook.ts";
import dayjs from "dayjs";
import router from "../plugins/router.ts";

let user = JSON.parse(sessionStorage.getItem("user"));
let pageConfig = reactive({
  currentPage: 1,
  pages: 0,
  total: 0,
  pageSize: 8,
  songList: []
})

let isPlaylistOrFavorite = ref(true)


onBeforeMount(() => {
  updatePlaylist()
  updateFavoritePlaylist()
})
let playlists = ref()
async function updatePlaylist() {
  console.log("更新了")
  playlists.value = await hook_findPlaylistsByUserId(user.id)
}
let favoritePlaylists = ref()
async function updateFavoritePlaylist() {
  favoritePlaylists.value = await hook_findFavoritePlaylistByUserId(user.id)
}


//emits
async function deleteSuccessUpdate(type: string) {
  console.log("收到了通知")
  if (type == "favoritePlaylist") {
    await updateFavoritePlaylist()
  } else if (type == "playlist") {
    console.log("1111")
    await updatePlaylist()
  }
}


onMounted(async () => {
  await updateCurrentPage()
})

//根据传递的currentPage来判断前后关系
const pageCollege = computed(() => {
  let currentPage = pageConfig.currentPage
  let pages = pageConfig.pages
  if (pages < 7) {
    return pages
  }
  if (currentPage <= 5) {
    return [1, 2, 3, 4, 5, '...', pages]
  } else if (currentPage > pages - 5) {
    return [1, '...', pages - 4, pages - 3, pages - 2, pages - 1, pages]
  } else {
    return [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', pages]
  }
})

//更新数据
async function updateCurrentPage() {
  let data = await hook_getSongPage(hook_getUser().id, pageConfig.currentPage, pageConfig.pageSize);
  console.log(data)
  pageConfig.songList = data["records"]
  pageConfig.total = data["total"]
  pageConfig.pages = data["pages"];
}

//点击确定的一页
function currentPage(page) {
  pageConfig.currentPage = page
  updateCurrentPage()
  updatePlaylist()
}

//上一页
function afterPage() {
  if (pageConfig.currentPage === 1) {
    pageConfig.currentPage = 1
  } else {
    pageConfig.currentPage = pageConfig.currentPage - 1
  }
  updateCurrentPage()
  updatePlaylist()
}

//下一页
function nextPage() {
  if (pageConfig.currentPage == pageConfig.pages) {
    pageConfig.currentPage = pageConfig.pages
  } else {
    pageConfig.currentPage = pageConfig.currentPage + 1
  }
  updateCurrentPage()
  updatePlaylist()
}


//添加歌单的数据
let data_addPlaylist = reactive(new Playlist("","",hook_getUser()?.['id']));
//数据添加后更新界面
async function addPlaylist() {
  await hook_addPlaylist(data_addPlaylist);
  playlists.value = await hook_findPlaylistsByUserId(user.id)

}


function editUser() {
  router.push('/edit')
}


</script>

<style scoped>

</style>